package common

import (
	"crypto/md5"
	"encoding/hex"
	"io"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
)

func tailCut(s string, cut string) string {
	S := []rune(cut)
	D := []rune(s)

	var position int
	flag := true
	j := len(S)
	for i := len(D); i > 0; i-- {
		if '/' != D[i-1] && D[i-1] == S[j-1] {
			if flag {
				position = i
			}
			j--
			if 0 == j {
				j = len(S)
			}
			flag = false
		} else {
			flag = true
			if D[i-1] == '/' && j == len(S) && 0 != position {
				break
			}
		}
	}
	r := D[0:position]
	return string(r)
}

func GetCurrentPath() string {
	var path string
	execName := os.Args[0]

	OK := strings.Contains(execName, "go_build_")
	if !OK {
		path = filepath.Dir(execName)
	} else {
		_, f, _, ok := runtime.Caller(0)
		if ok {
			regStr := `_([^_.]+)(\.exe){0,1}$`
			compile := regexp.MustCompile(regStr)
			subMatch := compile.FindSubmatch([]byte(execName))
			tail := string(subMatch[1])

			p := filepath.Dir(f)
			path = tailCut(p, tail)
		}
	}

	return path
}

func GetMD5sum(filepath string) (string, error) {
	file, err := os.Open(filepath)
	if err != nil {
		log.Println(err)
		return "", err
	}

	hash := md5.New()
	_, err = io.Copy(hash, file)
	if err != nil {
		log.Println(err)
		return "", err
	}

	sum := hash.Sum(nil)
	value := hex.EncodeToString(sum)
	return value, nil
}

func Compress(fold string) string {
	return ""
}
